package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.model.Message;
import com.example.forum.service.impl.MessageServiceImpl;
import com.example.forum.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api("信息接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageServiceImpl messageService;


    @ApiOperation("发送信息")
    @RequestMapping("/send")
    public AppResult send(@RequestParam("receive_user_id") @ApiParam("接收用户id") @NonNull Long id,
                          @RequestParam("content") @ApiParam("发送内容") @NonNull String content,
                          HttpServletRequest request) {

        String stringUserId = JWTUtils.getUserId(request.getHeader("user_token"));
        Long userId = Long.parseLong(stringUserId);
        if(userId.equals(id)) {
            return AppResult.fail("当前状态不允许发送信息");
        }
        Integer ret = messageService.addMessage(id,content,userId);
        if(ret == null || ret <= 0) {
            return AppResult.fail("发送失败");
        }
        return AppResult.success("发送成功");
    }

    @ApiOperation("获取用户的所有的站内信")
    @GetMapping("/getAll")
    public AppResult getAll(HttpServletRequest request) {
        String stringUserId = JWTUtils.getUserId(request.getHeader("user_token"));
        Long userId = Long.parseLong(stringUserId);
        List<Message> lists = messageService.selectMessageByUserId(userId);
        return AppResult.success(lists);

    }

    @ApiOperation("读取未读信息")
    @PostMapping("/markRead")
    public AppResult markRead(@RequestParam("id") @ApiParam("信息id") @NonNull Long id) {
        Integer ret = messageService.updateMessageStatus(id);
        if(ret == null || ret <= 0) {
            return AppResult.fail("读取失败");
        }
        return AppResult.success("读取成功");
    }

    @ApiOperation("回复信息")
    @PostMapping("/reply")
    public AppResult reply(@RequestParam("repliedId") @ApiParam("接收用户id") @NonNull Long id,
                           @RequestParam("content") @ApiParam("发送信息") @NonNull String content,
                           HttpServletRequest request) {
        Integer ret = messageService.addReplyMessage(id,content);
        if(ret == null || ret <= 0) {
            return AppResult.fail("回复失败");
        }
        return AppResult.success("回复成功");
    }

    @ApiOperation("获取用户未读取的文章数")
    @GetMapping("/getUnreadCount")
    public AppResult getUnreadCount() {
        Integer ret = messageService.getNotReadCount();
        return AppResult.success(ret);
    }
}
